package com.luck.picture.lib;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ScaleDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.glidetarget.ScaleImageTarge;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.BitmapUtil;
import com.luck.picture.lib.tools.DebugUtil;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.luck.picture.lib.tools.ScreenUtils;
import com.luck.picture.lib.widget.PreviewViewPager;
import com.luck.picture.lib.widget.ZoomImageView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * author：luck
 * project：PictureSelector
 * package：com.luck.picture.ui
 * email：邮箱->893855882@qq.com
 * data：17/01/18
 */
public class PictureExternalPreviewActivity extends PictureBaseActivity implements View.OnClickListener {
    private ImageView delete_iv;
    private ImageView download_iv;
    private ImageView return_iv;
    private TextView tv_title;
    private TextView tv_describe;
    private PreviewViewPager viewPager;
    private List<LocalMedia> images = new ArrayList<>();
    private int position = 0;
    private String directory_path;
    private SimpleFragmentAdapter adapter;
    private LayoutInflater inflater;
    private RxPermissions rxPermissions;
    private loadDataThread loadDataThread;
    public static final String PIC_LIST = "pic_list";
    public static final String POS = "pos";
    int type = 0;
    private float downX;    //按下时 的X坐标
    private float downY;    //按下时 的Y坐标
    private int screenWidth;
    private int screenHeight;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture_activity_external_preview);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();
        inflater = LayoutInflater.from(this);
        tv_title = (TextView) findViewById(R.id.picture_title);
        tv_describe = (TextView) findViewById(R.id.picture_describe);
        delete_iv = (ImageView) findViewById(R.id.right_delete);
        download_iv = (ImageView) findViewById(R.id.right_download);
        return_iv = (ImageView) findViewById(R.id.left_return);
        viewPager = (PreviewViewPager) findViewById(R.id.preview_pager);
        position = getIntent().getIntExtra(PictureConfig.EXTRA_POSITION, 0);
        directory_path = getIntent().getStringExtra(PictureConfig.DIRECTORY_PATH);
        type = getIntent().getIntExtra("type", 1);
        if (type == 1) {
            delete_iv.setVisibility(View.GONE);
            download_iv.setVisibility(View.GONE);
            return_iv.setVisibility(View.GONE);
        } else if (type == 2) {
            delete_iv.setVisibility(View.GONE);
            download_iv.setVisibility(View.VISIBLE);
            return_iv.setVisibility(View.VISIBLE);
        }
        images = (List<LocalMedia>) getIntent().getSerializableExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST);
        delete_iv.setOnClickListener(this);
        return_iv.setOnClickListener(this);
        initViewPageAdapterData();
    }

    private void initViewPageAdapterData() {
        tv_title.setText(position + 1 + "/" + images.size());
        adapter = new SimpleFragmentAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tv_title.setText(position + 1 + "/" + images.size());
                LocalMedia media = images.get(position);
                Log.e("dddss", media.toString());
                setDescribShow(media);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == delete_iv) {
            if (viewPager.getCurrentItem() < images.size()) {
                images.remove(viewPager.getCurrentItem());
                adapter.notifyDataSetChanged();
            }
            tv_title.setText(viewPager.getCurrentItem() + 1 + "/" + images.size());
            if (images.size() == 0) {
                setResultes(null, -1);
            }
        } else if (v == return_iv) {
            finish();
            overridePendingTransition(0, R.anim.a3);
        }
    }

    public class SimpleFragmentAdapter extends PagerAdapter {
        boolean isNormal = true;

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            (container).removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            // return super.getItemPosition(object);
            return POSITION_NONE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            View contentView = inflater.inflate(R.layout.picture_image_preview, container, false);
            final ZoomImageView imageView = (ZoomImageView) contentView.findViewById(R.id.preview_image);
            final ScrollView scroll = (ScrollView) contentView.findViewById(R.id.scroll);
            final ZoomImageView normalImageView = (ZoomImageView) contentView.findViewById(R.id.preview_image_normal);
            imageView.setOneImgClick(new ZoomImageView.oneImgClick() {
                @Override
                public void oneClickListener() {
                    finish();
                    overridePendingTransition(0, R.anim.a3);
                }
            });
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ((type == 2)) {
                        if (download_iv.getVisibility() == View.GONE || download_iv.getVisibility() == View.INVISIBLE) {
                            download_iv.setVisibility(View.VISIBLE);
                            return_iv.setVisibility(View.VISIBLE);
                            tv_title.setVisibility(View.VISIBLE);
                        } else {
                            download_iv.setVisibility(View.INVISIBLE);
                            return_iv.setVisibility(View.INVISIBLE);
                            tv_title.setVisibility(View.INVISIBLE);
                        }
                    }
                }
            });
            imageView.setOnTouchListener(new View.OnTouchListener() {
                int count = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (count < event.getPointerCount()) {
                        count = event.getPointerCount();
                    }
                    if (count > 1) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            count = 0;
                        }
                        return imageView.onTouch(v, event);
                    }
                    //在触发时回去到起始坐标
                    float x = event.getX();
                    float y = event.getY();
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            //将按下时的坐标存储
                            downX = x;
                            downY = y;
                            break;

                        case MotionEvent.ACTION_UP:

                            if (count == 1) {
                                //获取到距离差
                                float dx = x - downX;
                                float dy = y - downY;
                                if (Math.abs(dx) < 5 && Math.abs(dy) < 5) {
                                    v.performClick();
                                }
                                //防止是按下也判断
                                if (Math.abs(dx) < 100 && Math.abs(dy) > 200) {
                                    //通过距离差判断方向
                                    if (isSlideDown(dx, dy)) {

                                        finish();
                                        overridePendingTransition(0, R.anim.a3);
                                    }
                                }
                            }
                            count = 0;
                            break;
                    }
                    return true;

                }
            });
            normalImageView.setOneImgClick(new ZoomImageView.oneImgClick() {
                @Override
                public void oneClickListener() {
                    finish();
                    overridePendingTransition(0, R.anim.a3);
                }
            });
            normalImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if ((type == 2)) {
                        if (download_iv.getVisibility() == View.GONE || download_iv.getVisibility() == View.INVISIBLE) {
                            download_iv.setVisibility(View.VISIBLE);
                            return_iv.setVisibility(View.VISIBLE);
                            tv_title.setVisibility(View.VISIBLE);
                        } else {
                            download_iv.setVisibility(View.INVISIBLE);
                            return_iv.setVisibility(View.INVISIBLE);
                            tv_title.setVisibility(View.INVISIBLE);
                        }
                    }
                }
            });
            normalImageView.setOnTouchListener(new View.OnTouchListener() {
                int count = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (count < event.getPointerCount()) {
                        count = event.getPointerCount();
                    }
                    if (count > 1) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            count = 0;
                        }
                        return normalImageView.onTouch(v, event);
                    }
                    //在触发时回去到起始坐标
                    float x = event.getX();
                    float y = event.getY();
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            //将按下时的坐标存储
                            downX = x;
                            downY = y;
                            break;

                        case MotionEvent.ACTION_UP:

                            if (count == 1) {
                                //获取到距离差
                                float dx = x - downX;
                                float dy = y - downY;
                                if (Math.abs(dx) < 5 && Math.abs(dy) < 5) {
                                    v.performClick();
                                }
                                //防止是按下也判断
                                if (Math.abs(dx) < 100 && Math.abs(dy) > 200) {
                                    //通过距离差判断方向
                                    if (isSlideDown(dx, dy)) {

                                        finish();
                                        overridePendingTransition(0, R.anim.a3);
                                    }
                                }
                            }
                            count = 0;
                            break;
                    }
                    return true;

                }
            });
            LocalMedia media = images.get(position);
            if (media != null) {
                final String pictureType = media.getPictureType();
                final String path;
                if (type == 2) {
                    setDescribShow(media);
                } else {
                    if (position == 0) {
                        setDescribShow(media);
                    }
                }
//
                if (media.isCut() && !media.isCompressed()) {
                    // 裁剪过
                    path = media.getCutPath();
                } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                    // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                    path = media.getCompressPath();
                } else {
                    path = media.getPath();
                }
                boolean isHttp = PictureMimeType.isHttp(path);
                // 可以长按保存并且是网络图片显示一个对话框
                if (isHttp) {
                    showPleaseDialog();
                }
                boolean isGif = PictureMimeType.isGif(pictureType);
                // 压缩过的gif就不是gif了
                if (isGif && !media.isCompressed()) {
                    Glide.with(PictureExternalPreviewActivity.this)
                            .load(path)
                            .asGif()
                            .error(R.drawable.icon_def_1_1)
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .listener(new RequestListener<String, GifDrawable>() {
                                @Override
                                public boolean onException(Exception e, String model, Target<GifDrawable> target, boolean isFirstResource) {
                                    dismissDialog();
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(GifDrawable resource, String model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                    dismissDialog();
                                    return false;
                                }
                            })
                            .into(imageView);
                } else {
                    if (PictureMimeType.isGifPic(path)) {
                        Glide.with(PictureExternalPreviewActivity.this)
                                .load(path)
                                .asGif()
                                .error(R.drawable.icon_def_1_1)
                                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                .listener(new RequestListener<String, GifDrawable>() {
                                    @Override
                                    public boolean onException(Exception e, String model, Target<GifDrawable> target, boolean isFirstResource) {
                                        dismissDialog();
                                        return false;
                                    }

                                    @Override
                                    public boolean onResourceReady(GifDrawable resource, String model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                        dismissDialog();
                                        return false;
                                    }
                                })
                                .into(imageView);
                    }
//                    ScaleImageTarge sit = new ScaleImageTarge(imageView);
//                    sit.setScreenSize(ScreenUtils.getScreenWidth(PictureExternalPreviewActivity.this), ScreenUtils.getScreenHeight(PictureExternalPreviewActivity.this));
//                    Glide.with(PictureExternalPreviewActivity.this)
//                            .load(path)
//                            .into(sit);

                    Glide.with(PictureExternalPreviewActivity.this)
                            .load(path)
                            .listener(new RequestListener<String, GlideDrawable>() {
                                @Override
                                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                                    if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
//                                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//                                    }
                                    if( resource.getIntrinsicHeight() / resource.getIntrinsicWidth() < 2){
                                        isNormal = true;
                                    }else{
                                        isNormal =false;
                                    }
                                    if (isNormal) {
                                        normalImageView.setVisibility(View.VISIBLE);
                                        scroll.setVisibility(View.GONE);
                                        Glide.with(PictureExternalPreviewActivity.this)
                                                .load(path)
                                                .fitCenter().error(R.drawable.icon_def_1_1)
                                                .into(normalImageView);
                                    } else {
                                        normalImageView.setVisibility(View.GONE);
                                        scroll.setVisibility(View.VISIBLE);
                                        Glide.with(PictureExternalPreviewActivity.this)
                                                .load(path)
                                                .error(R.drawable.icon_def_1_1)
                                                .into(imageView);
                                    }
                                    return false;
                                }
                            }).error(R.drawable.icon_def_1_1)
                            .into(imageView);


//                            .fitCenter()

                    dismissDialog();
                }
                download_iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (rxPermissions == null) {
                            rxPermissions = new RxPermissions(PictureExternalPreviewActivity.this);
                        }
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(new Observer<Boolean>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                    }

                                    @Override
                                    public void onNext(Boolean aBoolean) {
                                        if (aBoolean) {
                                            downloadPic(path);
                                        } else {
                                            showToast(getString(R.string.picture_jurisdiction));
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onComplete() {
                                    }
                                });
                    }
                });
//                imageView.setOnLongClickListener(new View.OnLongClickListener() {
//                    @Override
//                    public boolean onLongClick(View v) {
//                        if (rxPermissions == null) {
//                            rxPermissions = new RxPermissions(PictureExternalPreviewActivity.this);
//                        }
//                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                                .subscribe(new Observer<Boolean>() {
//                                    @Override
//                                    public void onSubscribe(Disposable d) {
//                                    }
//
//                                    @Override
//                                    public void onNext(Boolean aBoolean) {
//                                        if (aBoolean) {
//                                            showDownLoadDialog(path);
//                                        } else {
//                                            showToast(getString(R.string.picture_jurisdiction));
//                                        }
//                                    }
//
//                                    @Override
//                                    public void onError(Throwable e) {
//                                    }
//
//                                    @Override
//                                    public void onComplete() {
//                                    }
//                                });
//                        return true;
//                    }
//                });
            }
            (container).addView(contentView, 0);
            return contentView;
        }
    }

    private void setDescribShow(LocalMedia media) {
        if (TextUtils.isEmpty(media.getDescribe())) {
            tv_describe.setVisibility(View.GONE);
        } else {
            tv_describe.setVisibility(View.VISIBLE);
            tv_describe.setText(media.getDescribe());
        }
    }

    /**
     * 下载图片
     */
    private void downloadPic(final String path) {
        showPleaseDialog();
        boolean isHttp = PictureMimeType.isHttp(path);
        if (isHttp) {
            loadDataThread = new loadDataThread(path);
            loadDataThread.start();
        } else {
            // 有可能本地图片
            try {
                String dirPath = PictureFileUtils.createDir(PictureExternalPreviewActivity.this,
                        System.currentTimeMillis() + ".png", directory_path);
                PictureFileUtils.copyFile(path, dirPath);
                showToast(getString(R.string.picture_save_success) + "\n" + dirPath);
                dismissDialog();
            } catch (IOException e) {
                showToast(getString(R.string.picture_save_error) + "\n" + e.getMessage());
                dismissDialog();
                e.printStackTrace();
            }
        }
//        final CustomDialog dialog = new CustomDialog(PictureExternalPreviewActivity.this,
//                ScreenUtils.getScreenWidth(PictureExternalPreviewActivity.this) * 3 / 4,
//                ScreenUtils.getScreenHeight(PictureExternalPreviewActivity.this) / 4,
//                R.layout.picture_wind_base_dialog_xml, R.style.Theme_dialog);
//        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
//        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
//        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
//        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
//        tv_title.setText(getString(R.string.picture_prompt));
//        tv_content.setText(getString(R.string.picture_prompt_content));
//        btn_cancel.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                dialog.dismiss();
//            }
//        });
//        btn_commit.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showPleaseDialog();
//                boolean isHttp = PictureMimeType.isHttp(path);
//                if (isHttp) {
//                    loadDataThread = new loadDataThread(path);
//                    loadDataThread.start();
//                } else {
//                    // 有可能本地图片
//                    try {
//                        String dirPath = PictureFileUtils.createDir(PictureExternalPreviewActivity.this,
//                                System.currentTimeMillis() + ".png", directory_path);
//                        PictureFileUtils.copyFile(path, dirPath);
//                        showToast(getString(R.string.picture_save_success) + "\n" + dirPath);
//                        dismissDialog();
//                    } catch (IOException e) {
//                        showToast(getString(R.string.picture_save_error) + "\n" + e.getMessage());
//                        dismissDialog();
//                        e.printStackTrace();
//                    }
//                }
//                dialog.dismiss();
//            }
//        });
//        dialog.show();
    }


    // 进度条线程
    public class loadDataThread extends Thread {
        private String path;

        public loadDataThread(String path) {
            super();
            this.path = path;
        }

        public void run() {
            try {
                showLoadingImage(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    // 下载图片保存至手机
    public void showLoadingImage(String urlPath) {
        try {
            URL u = new URL(urlPath);
            String path = PictureFileUtils.createDir(PictureExternalPreviewActivity.this,
                    System.currentTimeMillis() + ".png", PictureFileUtils.CAMERA_PIC_PATH);
            byte[] buffer = new byte[1024 * 8];
            int read;
            int ava = 0;
            long start = System.currentTimeMillis();
            BufferedInputStream bin;
            bin = new BufferedInputStream(u.openStream());
            BufferedOutputStream bout = new BufferedOutputStream(
                    new FileOutputStream(path));
            while ((read = bin.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
                ava += read;
                long speed = ava / (System.currentTimeMillis() - start);
                DebugUtil.i("Download: " + ava + " byte(s)"
                        + "    avg speed: " + speed + "  (kb/s)");
            }
            bout.flush();
            bout.close();
            Message message = handler.obtainMessage();
            message.what = 200;
            message.obj = path;
            handler.sendMessage(message);
        } catch (IOException e) {
            dismissDialog();
            showToast(getString(R.string.picture_save_error) + "\n" + e.getMessage());
            e.printStackTrace();
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    String path = (String) msg.obj;
                    showToast(getString(R.string.picture_save_success) + "\n" + path);
                    dismissDialog();
                    break;
            }
        }
    };

    @Override
    public void onBackPressed() {
        setResultes(images, 1);
        overridePendingTransition(0, R.anim.a3);
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loadDataThread != null) {
            handler.removeCallbacks(loadDataThread);
            loadDataThread = null;
        }
    }

    private void setResultes(List<LocalMedia> images, int position) {
        Intent intent = getIntent();
        intent.putExtra(POS, position);
        if (position > 0) {
            intent.putExtra(PIC_LIST, (Serializable) images);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 根据距离差判断 滑动方向
     *
     * @param dx X轴的距离差
     * @param dy Y轴的距离差
     * @return 滑动的方向
     */
    private boolean isSlideDown(float dx, float dy) {
        Log.e("Tag", "========X轴距离差：" + dx);
        Log.e("Tag", "========Y轴距离差：" + dy);
        if (Math.abs(dx) < Math.abs(dy)) {
            return dy > 0;
        } else {
            return false;
        }
    }

}
